package com.lims.feign;

import com.lims.common.Conts;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Enumeration;
import java.util.List;

/**
 * feign调用拦截器，可以将当前服务接口的头参传入feign调用的接口，直接透传
 */
@Slf4j
public class FeignInterceptor implements RequestInterceptor {

    @Value("${spring.application.name}")
    private String appName;


    private List<String> headers = List.of(Conts.MOBILE);

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(attributes != null){
            HttpServletRequest request = attributes.getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            String innerReq = null;
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    if(headers.contains(name.toLowerCase())){
                        String values = request.getHeader(name);
                        requestTemplate.header(name, values);
                    }
                    if(Conts.INNER_REQ.toLowerCase().equals(name.toLowerCase())){
                        innerReq = request.getHeader(name);
                    }
                }
            }
            //请求链路追踪标志,当前应用名拼接在最后,多个微服务之间互相调用，记录调用链路
            if(innerReq == null){
                requestTemplate.header(Conts.INNER_REQ,appName);
            }else {
                requestTemplate.header(Conts.INNER_REQ,innerReq + "->" + appName);
            }
            requestTemplate.header(Conts.TRACE_ID,MDC.get(Conts.TRACE_ID));
            log.debug("FeignInterceptor头参:{}", requestTemplate.headers());
        }
    }
}
